package com.zone.domain.strategy.service.armory.assemble.impl;

import com.google.common.collect.Lists;
import com.zone.domain.strategy.model.entity.StrategyAwardEntity;
import com.zone.domain.strategy.model.entity.StrategyEntity;
import com.zone.domain.strategy.model.entity.StrategyRuleEntity;
import com.zone.domain.strategy.model.valobj.RuleEnums;
import com.zone.domain.strategy.repository.IStrategyRepository;
import com.zone.types.exception.BizException;
import com.zone.types.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: zongzi
 * @description: 权重奖品策略装配器
 * @date: 2024/5/29
 */
@Slf4j
@Service
public class RuleWeightStrategyAssembleHandler extends AbstractStrategyAssembleHandler {
    @Autowired
    private IStrategyRepository strategyRepository;

    @Override
    public void assembleStrategy(Long strategyId, List<StrategyAwardEntity> strategyAwardEntityList) {
        StrategyEntity strategyEntity = strategyRepository.getStrategyEntity(strategyId);
        List<String> ruleModels = strategyEntity.parseRuleModels();
        if (!ruleModels.contains(RuleEnums.RuleModelEnum.RULE_WEIGHT.getCode())) {
            return;
        }
        // 抽奖活动配置了权重，但是未查询到权重规则配置。抛出异常
        List<StrategyRuleEntity> strategyRuleEntityList = strategyRepository.queryStrategyRules(strategyId, RuleEnums.RuleModelEnum.RULE_WEIGHT.getCode());
        if (CollectionUtils.isEmpty(strategyRuleEntityList)) {
            throw new BizException(String.format("抽奖权重数据装配，未查询到权重配置，活动描述：%s", strategyEntity.getStrategyDesc()));
        }

        for (StrategyRuleEntity strategyRuleEntity : strategyRuleEntityList) {
            Map<String, List<Integer>> parseRuleValues = strategyRuleEntity.parseRuleWeightValues();
            for (String ruleWeight : parseRuleValues.keySet()) {
                List<Integer> awardIds = parseRuleValues.getOrDefault(ruleWeight, Lists.newArrayList());
                List<StrategyAwardEntity> filterStrategyAwardEntityList = strategyAwardEntityList.stream()
                        .filter(strategyAwardEntity -> awardIds.contains(strategyAwardEntity.getAwardId()))
                        .collect(Collectors.toList());
                super.assemble(String.format("%s_%s", strategyId, ruleWeight), filterStrategyAwardEntityList);
            }
        }
    }
}
